<template>
    <div class="edit-pet-form">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="全名" prop="全名">
                <el-input v-model="form.全名" placeholder="请输入宠物全名"></el-input>
            </el-form-item>

            <el-form-item label="别名" prop="别名">
                <el-input v-model="form.别名" placeholder="请输入宠物别名"></el-input>
            </el-form-item>

            <el-form-item label="分类" prop="分类">
                <el-select 
                    v-model="form.分类" 
                    placeholder="请选择分类" 
                    filterable 
                    allow-create
                    :before-create="handleBeforeCreate">
                    <el-option 
                        v-for="category in categories" 
                        :key="category" 
                        :label="category"
                        :value="category">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="体型" prop="体型">
                <el-input v-model="form.体型" placeholder="请输入体型"></el-input>
            </el-form-item>

            <el-form-item label="毛发" prop="毛发">
                <el-input v-model="form.毛发" placeholder="请输入毛发特征"></el-input>
            </el-form-item>

            <el-form-item label="智商" prop="智商">
                <el-input v-model="form.智商" placeholder="请输入智商"></el-input>
            </el-form-item>

            <el-form-item label="寿命" prop="寿命">
                <el-input v-model="form.寿命" placeholder="请输入寿命"></el-input>
            </el-form-item>

            <el-form-item label="饲养" prop="饲养">
                <el-input v-model="form.饲养" type="textarea" :rows="3" placeholder="请输入饲养信息"></el-input>
            </el-form-item>

            <el-form-item label="功能" prop="功能">
                <el-input v-model="form.功能" placeholder="请输入功能"></el-input>
            </el-form-item>

            <el-form-item label="原产地" prop="原产地">
                <el-input v-model="form.原产地" placeholder="请输入原产地"></el-input>
            </el-form-item>

            <el-form-item label="价格" prop="价格">
                <el-input v-model="form.价格" placeholder="请输入价格"></el-input>
            </el-form-item>

            <el-form-item label="图片" prop="imgPath">
                <el-upload
                    class="avatar-uploader"
                    :action="`${baseURL}/image/upload`"
                    :show-file-list="false"
                    :on-success="handleUploadSuccess"
                    :on-error="handleUploadError"
                    :before-upload="beforeUpload">
                    <img v-if="imageUrl" :src="getImageUrl(form.imgPath)" class="avatar">
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <div class="image-tip">支持 jpg、jpeg、png 格式，大小不超过 500KB</div>
            </el-form-item>

            <el-form-item label="简介" prop="简介">
                <el-input v-model="form.简介" type="textarea" :rows="4" placeholder="请输入宠物简介"></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm">确认</el-button>
                <el-button @click="$emit('cancel')">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { updatePet, getPetCategories } from '@/api/admin';
import { getimage } from '@/api/image';
import request from "@/util/http";

const props = defineProps({
    petData: {
        type: Object,
        required: true
    }
});

const emit = defineEmits(['cancel', 'success']);
const baseURL = request.defaults.baseURL;

const formRef = ref(null);
const categories = ref([]);
const imageUrl = ref('');

const form = ref({
    全名: '',
    别名: '',
    分类: '',
    体型: '',
    毛发: '',
    智商: '',
    寿命: '',
    饲养: '',
    功能: '',
    原产地: '',
    价格: '',
    imgPath: '',
    简介: ''
});

const rules = {
    全名: [{ required: true, message: '请输入宠物全名', trigger: 'blur' }],
    分类: [{ required: true, message: '请选择宠物分类', trigger: 'change' }],
    简介: [{ required: true, message: '请输入宠物简介', trigger: 'blur' }]
};

const fetchCategories = async () => {
    try {
        const { data } = await getPetCategories();
        if (data.code === 200) {
            categories.value = data.data;
        }
    } catch (error) {
        ElMessage.error('获取分类失败：' + error.message);
    }
};

const submitForm = async () => {
    if (!formRef.value) return;

    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const { data } = await updatePet(props.petData.id, form.value);
                if (data.code === 200) {
                    ElMessage.success('更新成功');
                    emit('success');
                } else {
                    ElMessage.error(data.message || '更新失败');
                }
            } catch (error) {
                ElMessage.error('更新失败：' + error.message);
            }
        }
    });
};

// 图片上传相关方法
const handleUploadSuccess = (res) => {
    if (res.code === 200 || res.url) {
        form.value.imgPath = res.url;
        imageUrl.value = getImageUrl(res.url);
        ElMessage.success('图片上传成功');
    } else {
        ElMessage.error(res.error || '上传失败');
    }
};

const handleUploadError = (error) => {
    ElMessage.error('图片上传失败：' + error.message);
};

const beforeUpload = (file) => {
    const isAllowed = ['image/jpeg', 'image/jpg', 'image/png'].includes(file.type);
    const isLt500K = file.size / 1024 < 500;

    if (!isAllowed) {
        ElMessage.error('只能上传 JPG/PNG 格式的图片！');
        return false;
    }
    if (!isLt500K) {
        ElMessage.error('图片大小不能超过 500KB！');
        return false;
    }
    return true;
};

const getImageUrl = (path) => {
    if (!path) return '';
    return getimage(path);
};

onMounted(() => {
    fetchCategories();
    // 初始化表单数据
    form.value = {
        全名: props.petData.全名,
        别名: props.petData.别名,
        分类: props.petData.分类,
        体型: props.petData.体型,
        毛发: props.petData.毛发,
        智商: props.petData.智商,
        寿命: props.petData.寿命,
        饲养: props.petData.饲养,
        功能: props.petData.功能,
        原产地: props.petData.原产地,
        价格: props.petData.价格,
        imgPath: props.petData.imgPath,
        简介: props.petData.简介
    };
    // 设置初始图片
    if (props.petData.imgPath) {
        imageUrl.value = getImageUrl(props.petData.imgPath);
    }
});

// 添加新方法
const handleBeforeCreate = (value) => {
    // 检查是否已存在该分类
    if (categories.value.includes(value)) {
        ElMessage.warning('该分类已存在');
        return false;
    }
    // 检查分类名称长度
    if (value.length > 20) {
        ElMessage.warning('分类名称不能超过20个字符');
        return false;
    }
    // 添加到分类列表中
    categories.value.push(value);
    return true;
};
</script>

<style scoped>
.edit-pet-form {
    padding: 20px;
}

.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
}

.avatar-uploader:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.image-tip {
    font-size: 12px;
    color: #666;
    margin-top: 5px;
}
</style>